import email
import imaplib
import smtplib
from email.header import decode_header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import getpass


# 发送邮件类 jhpealhtmuaedige
class EmailSender:
    def __init__(self, sending, password, furl, title, body):
        self.sending = sending
        self.password = password
        self.furl = furl
        self.title = title
        self.body = body

    def send_email(self):
        # 创建邮件对象
        msg = MIMEMultipart()
        msg['From'] = self.sending
        msg['To'] = ', '.join(self.furl)
        msg['Subject'] = self.title

        # 添加邮件正文
        msg.attach(MIMEText(self.body, 'plain'))

        # 连接到 SMTP 服务器
        server = smtplib.SMTP('smtp.qq.com', 587)
        server.starttls()  # 启用 TLS 加密
        server.login(self.sending, self.password)

        # 发送邮件
        text = msg.as_string()
        server.sendmail(self.sending, self.furl, text)

        # 关闭连接
        server.quit()


class EmailRead:
    def __init__(self, email_address, password):
        self.email_address = email_address
        self.password = password

    def read_emails(self, mailbox='INBOX'):
        # 连接到 IMAP 服务器
        imap_server = 'imap.qq.com'
        imap_port = 993  # QQ 邮箱的 IMAP 端口
        mail = imaplib.IMAP4_SSL(imap_server, imap_port)
        mail.login(self.email_address, self.password)
        mail.select(mailbox)

        # 搜索邮件
        status, messages = mail.search(None, 'ALL')
        messages = messages[0].split(b' ')

        for msg_num in messages:
            # 获取邮件内容
            status, data = mail.fetch(msg_num, '(RFC822)')
            raw_email = data[0][1]
            email_message = email.message_from_bytes(raw_email)

            # 解析邮件内容
            self.decode_email(email_message)

        # 关闭连接
        mail.close()
        mail.logout()

    def decode_email(self, email_message):
        # 解析邮件头部信息
        subject = decode_header(email_message['Subject'])[0][0]
        if isinstance(subject, bytes):
            subject = subject.decode()

        from_ = email.utils.parseaddr(email_message['From'])[1]

        # 打印邮件头部信息
        print(f'Subject: {subject}')
        print(f'From: {from_}')

        # 解析邮件正文
        if email_message.is_multipart():
            for part in email_message.walk():
                content_type = part.get_content_type()
                content_disposition = str(part.get('Content-Disposition'))
                try:
                    body = part.get_payload(decode=True).decode()
                except:
                    pass
                if content_type == 'text/plain' and 'attachment' not in content_disposition:
                    print(f'Body: {body}')
                    break
        else:
            content_type = email_message.get_content_type()
            body = email_message.get_payload(decode=True).decode()
            if content_type == 'text/plain':
                print(f'Body: {body}')


if __name__ == "__main__":
    num = input("1是发送邮件，2是读取邮件: ")

    if num == '1':
        # 输入发件人邮箱和密码
        sender_email = input("请输入您的QQ邮箱: ")
        sender_password = getpass.getpass("QQ邮箱的授权码: ")
        # sender_password = 'madidi666'

        # 输入收件人邮箱
        recipient_emails = input("输入收件人邮件地址，多个地址请用英文逗号分隔: ").split(',')

        # 输入邮件主题和正文
        title = input("请输入邮件主题: ")
        body = input("请输入邮件正文: ")

        # 发送邮件
        # send_email(title, body, sender_email, recipient_emails, sender_password)
        # 使用类发送邮件
        emailSender = EmailSender(sender_email, sender_password, recipient_emails, title, body)
        emailSender.send_email()

    elif num == '2':
        # 输入收件人邮箱和密码
        email_address = input("请输入您的QQ邮箱: ")
        sender_accept = getpass.getpass("QQ邮箱的授权码: ")

        # 读取邮件
        emailRead = EmailRead(email_address, sender_accept)
        emailRead.read_emails()
